import axios from 'axios';

// 根据环境决定API基础URL
// 开发环境使用代理，生产环境使用完整URL
const isDevelopment = import.meta.env.MODE === 'development';
let API_BASE_URL;

if (isDevelopment) {
  // 开发环境使用代理
  API_BASE_URL = '/api';
} else {
  // 生产环境使用环境变量或默认值
  const envUrl = import.meta.env.VITE_API_BASE_URL;
  if (envUrl && envUrl.trim() !== '') {
    API_BASE_URL = envUrl;
  } else {
    API_BASE_URL = 'http://localhost:8001';
  }
}

// 确保URL格式正确（移除末尾斜杠和空格）
API_BASE_URL = API_BASE_URL.trim().replace(/\/+$/, '');
console.log('API Base URL:', API_BASE_URL);

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  },
  // 添加跨域配置
  withCredentials: false
});

export const apiService = {
  // Search materials
  async searchMaterials(query, limit = 10) {
    try {
      const response = await apiClient.get('/materials/search', {
        params: { query, limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error searching materials:', error);
      throw error;
    }
  },

  // Get material details
  async getMaterialDetails(materialId) {
    try {
      const response = await apiClient.get(`/materials/${materialId}`);
      return response.data;
    } catch (error) {
      console.error('Error fetching material details:', error);
      throw error;
    }
  },

  // Get crystal structure
  async getCrystalStructure(materialId) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/structure`);
      return response.data;
    } catch (error) {
      console.error('Error fetching crystal structure:', error);
      throw error;
    }
  },

  // Get electronic structure
  async getElectronicStructure(materialId) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/electronic`);
      return response.data;
    } catch (error) {
      console.error('Error fetching electronic structure:', error);
      throw error;
    }
  },

  // Get example materials
  async getExampleMaterials() {
    try {
      const response = await apiClient.get('/examples');
      return response.data;
    } catch (error) {
      console.error('Error fetching examples:', error);
      throw error;
    }
  },

  // Get material papers
  async getMaterialPapers(materialId, limit = 100) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/papers`, {
        params: { limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error fetching material papers:', error);
      throw error;
    }
  },

  // Get material prices
  async getMaterialPrices(materialId, limit = 50) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/prices`, {
        params: { limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error fetching material prices:', error);
      throw error;
    }
  },

  // Search papers directly
  async searchPapers(query, limit = 100) {
    try {
      const response = await apiClient.get('/search/baidu/papers', {
        params: { query, limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error searching papers:', error);
      throw error;
    }
  },

  // Search prices directly
  async searchPrices(query, limit = 50) {
    try {
      const response = await apiClient.get('/search/baidu/prices', {
        params: { query, limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error searching prices:', error);
      throw error;
    }
  },

  // Health check
  async healthCheck() {
    try {
      const response = await apiClient.get('/health');
      return response.data;
    } catch (error) {
      console.error('Health check failed:', error);
      throw error;
    }
  },

  // AI Chat - Stream response
  async aiChatStream(prompt, materialData = null, temperature = 0.7, maxTokens = 7000) {
    try {
      const requestData = {
        prompt,
        material_data: materialData,
        temperature,
        max_tokens: maxTokens
      };

      // 使用正确的URL路径，确保通过代理
      const url = isDevelopment ? '/api/ai/chat' : `${API_BASE_URL}/ai/chat`;
      
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        throw new Error(`AI chat failed: ${response.statusText}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      
      return {
        async *[Symbol.asyncIterator]() {
          try {
            let buffer = '';
            
            while (true) {
              const { done, value } = await reader.read();
              if (done) break;

              buffer += decoder.decode(value, { stream: true });
              const lines = buffer.split('\n');
              
              // 保留最后一行（可能不完整）
              buffer = lines.pop() || '';
              
              for (const line of lines) {
                if (line.trim() && line.startsWith('data: ')) {
                  try {
                    const jsonStr = line.substring(6); // 移除 'data: ' 前缀
                    const data = JSON.parse(jsonStr);
                    
                    // 只返回content字段，不返回整个JSON对象
                    if (data.content !== undefined) {
                      yield { content: data.content, is_final: data.is_final || false };
                    }
                  } catch (e) {
                    console.warn('Failed to parse AI response:', e, 'Line:', line);
                  }
                }
              }
            }
            
            // 处理剩余的数据
            if (buffer.trim() && buffer.startsWith('data: ')) {
              try {
                const jsonStr = buffer.substring(6);
                const data = JSON.parse(jsonStr);
                
                if (data.content !== undefined) {
                  yield { content: data.content, is_final: data.is_final || false };
                }
              } catch (e) {
                console.warn('Failed to parse remaining AI response:', e);
              }
            }
          } finally {
            reader.releaseLock();
          }
        }
      };
      
    } catch (error) {
      console.error('Error in AI chat stream:', error);
      throw error;
    }
  },

  // AI Chat - Simple response (non-stream)
  async aiChatSimple(prompt, materialData = null, temperature = 0.7, maxTokens = 7000) {
    try {
      const requestData = {
        prompt,
        material_data: materialData,
        temperature,
        max_tokens: maxTokens
      };

      const response = await apiClient.post('/ai/chat/simple', requestData);
      return response.data;
    } catch (error) {
      console.error('Error in AI chat simple:', error);
      throw error;
    }
  }
};

export default apiService;